import 'dart:convert';
import 'dart:developer';

import 'package:backendview/main.dart';
import 'package:backendview/request/exp.dart';
import 'package:backendview/request/response_data.dart';
import 'package:dio/dio.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class MyDioLogger extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    super.onRequest(options, handler);
    try {
      final requestHeaders = <String, dynamic>{};

      requestHeaders['method'] = options.method;
      requestHeaders['url'] = "${options.baseUrl}${options.path}";
      if (options.data is FormData) {
        var data = {};
        options.data.fields.forEach(
            (MapEntry<String, dynamic> entry) => data[entry.key] = entry.value);
        requestHeaders['data'] = data;
      } else {
        requestHeaders['data'] = options.data?.toString();
      }
      requestHeaders['queryParameters'] = options.queryParameters.toString();
      requestHeaders.addAll(options.headers);
      var params = json.encoder.convert(requestHeaders);
      logger.v("request data: $params");
    } catch (e) {}
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    if (response.data != null) {
      try {
        var res = ResponseData.fromJson(response.data);
        if (res.code == ErrCode.apiExp.value) {
          log("请求成功：${res.data}");
        }
      } catch (e) {}
    }
    super.onResponse(response, handler);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    logger.e(
      """
      request:
        method: ${err.requestOptions.method}
        url: ${err.requestOptions.baseUrl}${err.requestOptions.path}
        headers: ${err.requestOptions.headers}
        data: ${err.requestOptions.data}
        queryParams: ${err.requestOptions.queryParameters}
      ---------------------------------------------------------------
      response:
        statusCode: ${err.response?.statusCode}
        data: ${err.response?.data}
      """,
    );
    EasyLoading.showToast("请求失败,请稍后再试");
    super.onError(err, handler);
  }
}
